package com.ccit.springbootlaw.mapper;

import com.ccit.springbootlaw.pojo.Root;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface RootMapper {
    // 根据ID查询管理员
    @Select("SELECT * FROM roots WHERE id = #{id}")
    Root findById(int id);

    // 根据传入实体进行多条件查询的方法（其中对用户名进行模糊查询）
    @Select("SELECT * FROM roots WHERE " +
            "(#{root.name} IS NULL OR #{root.name} = '' OR name LIKE CONCAT('%', #{root.name}, '%')) AND " +
            "(#{root.email} IS NULL OR #{root.email} = '' OR email LIKE CONCAT('%', #{root.email}, '%')) AND " +
            "(#{root.role} IS NULL OR #{root.role} = '' OR role = #{root.role}) AND " +
            "(#{root.createdAt} IS NULL OR created_at = #{root.createdAt}) AND " +
            "(#{root.updatedAt} IS NULL OR updated_at = #{root.updatedAt})")
    List<Root> findByRootWithUsernameLike(@Param("root") Root root);

    // 根据用户名或ID查询管理员，并验证密码
    @Select("SELECT * FROM roots WHERE (name = #{name} OR id = #{id}) AND password = #{password}")
    Root findByUsernameOrIdAndPassword(@Param("name") String name, @Param("id") int id, @Param("password") String password);

    // 插入新的管理员
    @Insert("INSERT INTO roots (name, email, password, role, created_at, updated_at) VALUES (#{name}, #{email}, #{password}, #{role}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertRoot(Root root);

    // 更新管理员信息
    @Update("<script>" +
            "UPDATE roots " +
            "<set>" +
            "<if test='name != null and name != \"\"'>name = #{name},</if>" +
            "<if test='email != null and email != \"\"'>email = #{email},</if>" +
            "<if test='password != null and password != \"\"'>password = #{password},</if>" +
            "<if test='role != null and role != \"\"'>role = #{role},</if>" +
            "updated_at = NOW()" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateRoot(Root root);

    // 删除管理员
    @Delete("DELETE FROM roots WHERE id = #{id}")
    int deleteRootById(int id);

    // 查询所有管理员
    @Select("SELECT * FROM roots")
    List<Root> findAllRoots();
}